package com.nameli.SIM.util.tree;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author NAME-L
 * @Description TODO
 * @className MyTreeUtils
 * @date 2021-11-10 15:50:11
 */

public class MyTreeUtils {
    private static final Log log = LogFactory.getLog(MyTreeUtils.class);

    private MyTreeUtils() {
    }

    public static <T> List<TreeNode<T>> listToTree(List<T> list, NodeMapper<T> mapper, Object id) {

        List<TreeNode<T>> tree = getTreeNodes(list, mapper);
        List<TreeNode<T>> rootTree = new ArrayList<>();
        tree.forEach((node) -> {
            //id 所有的根节点
            if (node.getParentId().equals(id)) {
                // 设置根节点的深度
                node.setDeep(0);
                //  添加到树中
                rootTree.add(node);
                // 找到当前节点的子节点
                getChild(node, tree);
            }
        });
        return rootTree;
    }

    private static <T> List<TreeNode<T>> getTreeNodes(List<T> list, NodeMapper<T> mapper) {
        List<TreeNode<T>> nodes = list.stream().map(row -> mapper.objectMapper(row)).collect(Collectors.toList());
        return nodes;
    }

    private static <T> void getChild(TreeNode<T> parentTree, List<TreeNode<T>> list) {
        list.forEach((child) -> {
            // 遍历的节点是父节点的子节点
            if (child.getParentId().equals(parentTree.getId())) {
                if (parentTree.getChildren() == null || parentTree.getChildren().size() == 0) {
                    parentTree.setChildren(new ArrayList<>());
                }
                child.setDeep(parentTree.getDeep() + 1);
                parentTree.getChildren().add(child);
                getChild(child, list);
            }
        });
    }
}
